// 节流timer
var timer;
// 防抖时间记录点
var prevTime = 0;
//执行次数
var count=0;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    title: {
      type: String,
      value: "导航栏"
    },
    zIndex: {
      type: Number,
      value: 1000
    },
    // 可选值 none 正常 throttle 节流  debounce 防抖
    mode: {
      type: String,
      value: "throttle"
    },
    //节流或防抖的间隔时间
    wait: {
      type: Number,
      value: 100
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    menuButton: {},
    systemInfo: {},
    height: 2, //整体高度
    mainHeight: 0, //操作区域高度
    opacity: 0
  },
  lifetimes: {
    attached() {
      this.setData({
        menuButton: wx.getMenuButtonBoundingClientRect(),
        systemInfo: wx.getSystemInfoSync()
      })
      this.initConfig();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //回调方法
    clickReturn() {
      this.triggerEvent("click")
    },
    initConfig() {
      const menuButton = this.data.menuButton;
      const systemInfo = this.data.systemInfo;
      let mainHeight = (menuButton.top - systemInfo.statusBarHeight) * 2 + menuButton.height;
      this.setData({
        height: mainHeight + systemInfo.statusBarHeight,
        mainHeight
      })
    },
    pageScrollChange(data) {
      let result = data / this.data.mainHeight;
      if (result > 1 && this.data.opacity >= 1) return false;
      // 闭包函数
      function setNavStatus() {
        count++;
        // console.log(count,'执行次数')
        this.setData({
          opacity: result
        })
        wx.setNavigationBarColor({
          frontColor: result < 1 ? "#ffffff" : "#000000",
          backgroundColor: '#ff0000',
          animation: {
            duration: 300,
            timingFunc: 'easeIn'
          }
        })
      }

      const {
        mode,
        wait
      } = this.data;

      /**
       * 防抖
       */
      function debounce() {
        clearInterval(timer);
        timer = setTimeout(() => {
          setNavStatus.call(this);
        }, wait)
      }
      //节流
      if (mode == 'throttle') {
        const nowTime = +new Date();
        if (prevTime + wait < nowTime) {
          prevTime = nowTime;
          setNavStatus.call(this);
        }
        // 无论如何都要执行最后一次操作
        debounce.call(this);
      } else if (mode == "debounce") {
        // 防抖
        debounce.call(this);
      
      } else {
        setNavStatus.call(this);
      }

    }
  }
})

// 导航栏高度是 （按钮上边距-状态栏高度）*2+按钮高度